
package com.zjxd.business.web.api.redis;

import java.util.Set;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;

/**
 * @author XRom
 * @version V1.0.0
 * @date 2018-01-04 13:12 redis缓存操作方法
 */
@Service
@Transactional
public class RedisServiceImpl implements RedisService {

	@Resource
	private RedisTemplate<String, Object>	redisTemplate;

	@Autowired
	private StringRedisTemplate				stringRedisTemplate;

	@Override
	public void set(String name, String key, String value) {

		stringRedisTemplate.opsForValue().set(name + key, value);
	}

	@Override
	public void set(String name, String key, String value, long millis) {

		stringRedisTemplate.opsForValue().set(name + key, value, millis, TimeUnit.SECONDS);
	}

	@Override
	public Object get(String name, String key) {

		return redisTemplate.opsForValue().get(name + key);
	}

	@Override
	public Long getExpire(String name, String key) {

		return stringRedisTemplate.getExpire(name + key);
	}

	@Override
	public void delete(String name, String key) {

		stringRedisTemplate.delete(name + key);
	}

	@Override
	public boolean hasKey(String name, String key) {

		return stringRedisTemplate.hasKey(name + key);
	}

	@Override
	public void setObj(String name, String key, Object value, long millis) {

		stringRedisTemplate.opsForValue().set(name + key, JSONObject.toJSON(value).toString(), millis, TimeUnit.SECONDS);
	}

	@Override
	public Set<String> getVagueKey(String name, String key) {

		Set<String> keyVal = redisTemplate.keys(name + key + "*");
		if (keyVal.size() == 0) { return null; }
		return keyVal;
	}

	@Override
	public <T> T getObj(String name, String key, Class<T> clazz) {

		String response = stringRedisTemplate.opsForValue().get(name + key);
		return JSONObject.toJavaObject(JSONObject.parseObject(response), clazz);
	}

	@Override
	public String getStr(String name, String key) {

		return stringRedisTemplate.opsForValue().get(name + key);
	}

	@Override
	public void setTimeOut(String name, String key, long millis) {

		redisTemplate.expire(name + key, millis, TimeUnit.SECONDS);
	}
}
